<template>
  <div>
    <search-cirteria>
      <template #prefix>
        <n-icon
          class="cursor-pointer"
          :component="ChevronBackOutline"
          @click="handleBack"
        />
      </template>
    </search-cirteria>
    <div class="table-container">
      <table-operate>
        <n-button
          size="small"
          type="primary"
          @click="handleShowModal"
        >
          <template #icon>
            <n-icon :component="AddSharp" />
          </template>
          新增
        </n-button>
      </table-operate>
      <data-table
        :columns="columns"
        :data="list"
        :loading="loading"
      />

      <pagination
        :total="total"
        v-model:page-num="pageNum"
        v-model:page-size="pageSize"
        @update:pageNum="query"
        @update:pageSize="query"
      />
    </div>
    <modal-form
      v-model:show="visible"
      title="字典管理"
      :config="dictFormConfig"
      v-model:form="form"
      @confirm="handleConfirm"
      @cancel="handleCancel"
    />
  </div>
</template>

<script lang="ts" setup>
  import { h } from 'vue'
  import { ChevronBackOutline, AddSharp } from '@vicons/ionicons5'
  import type { DataTableColumns } from 'naive-ui'
  import type { DictType, DictData } from '@/api/power/dict'
  import type { ModalFormConfig } from '@/components/ModalForm/index.vue'

  import { NButton, NFlex, NIcon, NTag } from 'naive-ui'
  import Pagination from '@/components/Pagination/index.vue'
  import TableOperate from '@/components/TableOperate/index.vue'
  import TableButton from '@/components/TableButton/index.vue'
  import ModalForm from '@/components/ModalForm/index.vue'
  import SearchCirteria from '@/components/SearchCriteria/index.vue'

  import {
    getDictData,
    saveDictData,
    updateDictData,
    getDictType,
    getDictDataList,
    deleteDictData
  } from '@/api/power/dict'
  import { useCurd } from '@/hooks/useCrud'
  import { useMessage } from 'naive-ui'
  import { useRouter, useRoute } from 'vue-router'

  import dayjs from 'dayjs'

  const message = useMessage()
  const route = useRoute()
  const router = useRouter()

  const id = route.params.id

  // 窗口显示/隐藏
  const visible = ref(false)

  const form = ref(<DictData>{
    sort: 0,
    status: '0'
  })

  const dictTypeInfo = ref(<DictType>{})

  // 获取字典类型详情
  const getDictTypeInfo = async () => {
    const res = await getDictType(+id)
    dictTypeInfo.value = res.data
    queryParams.value = { dictType: dictTypeInfo.value.dictType }
  }

  // 显示新增窗口
  const handleShowModal = async (id: any) => {
    if (typeof id === 'number') {
      const res = await getDictData(id)
      form.value = res.data
    }
    visible.value = true
  }

  // 确认保存
  const handleConfirm = async () => {
    if (form.value.id) {
      const { id, ...arg } = form.value
      arg.sort = Number(arg.sort)
      await updateDictData(id, arg)
      message.success('修改字典数据成功')
    } else {
      form.value.sort = Number(form.value.sort)
      await saveDictData({ ...form.value, dictType: dictTypeInfo.value.dictType })
      message.success('新增字典数据成功')
    }
    handleCancel()
    query()
  }

  const handleBack = () => {
    router.back()
  }

  // 取消保存
  const handleCancel = () => {
    form.value = {
      sort: 0,
      status: '0'
    }
    visible.value = false
  }

  const { query, handleDelete, list, queryParams, total, pageNum, pageSize, loading } =
    useCurd<DictData>({
      queryFn: getDictDataList,
      deleteFn: deleteDictData,
      beforeQuery: () => getDictTypeInfo()
    })

  const createColumns = (): DataTableColumns<Required<DictData>> => {
    return [
      {
        width: 200,
        align: 'center',
        title: '字典名称',
        key: 'label'
      },
      {
        width: 260,
        align: 'center',
        title: '字典值',
        key: 'value'
      },
      {
        title: '样式',
        key: 'listClass',
        render: row => renderListClass(row)
      },
      {
        title: '状态',
        key: 'status'
      },
      {
        title: '排序',
        key: 'sort'
      },
      {
        title: '创建时间',
        key: 'createTime',
        align: 'center',
        render: row => dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
      },
      {
        title: '操作',
        key: 'actions',
        align: 'center',
        width: 300,
        render(row) {
          return h(
            NFlex,
            { justify: 'center' },
            {
              default: () => [
                h(
                  TableButton,
                  {
                    type: 'primary',
                    onClick: () => handleShowModal(row.id)
                  },
                  {
                    default: () => '修改'
                  }
                ),
                h(
                  TableButton,
                  {
                    type: 'error',
                    onClick: () => handleDelete(row.id)
                  },
                  {
                    default: () => '删除'
                  }
                )
              ]
            }
          )
        }
      }
    ]
  }

  const columns = createColumns()

  const listClassOptions = [
    { label: '无', value: '' },
    { label: '默认', value: 'default' },
    { label: '成功', value: 'success' },
    { label: '警告', value: 'warning' },
    { label: '危险', value: 'error' },
    { label: '信息', value: 'info' }
  ]

  const dictFormConfig = ref<ModalFormConfig[]>([
    {
      type: 'input',
      label: '字典名称',
      key: 'label',
      show: true
    },
    {
      type: 'input',
      label: '字典值',
      key: 'value',
      show: true
    },
    {
      type: 'select',
      label: '表格样式',
      key: 'listClass',
      show: true,
      options: listClassOptions
    },
    {
      type: 'radio',
      label: '状态',
      key: 'status',
      show: true,
      options: [
        { label: '启用', value: '1' },
        { label: '禁用', value: '0' }
      ]
    },
    {
      type: 'input-number',
      label: '排序',
      key: 'sort',
      show: true
    },
    {
      type: 'input',
      label: '备注',
      key: 'remark',
      show: true
    }
  ])

  // 渲染表格样式
  const renderListClass = (row: DictData) => {
    if (row.listClass === '') {
      return h('span', null, { default: () => '无' })
    }
    const value = listClassOptions.find(item => item.value === row.listClass)?.label
    return h(NTag, { type: row.listClass as any }, { default: () => value })
  }
</script>

<style lang="scss">

</style>
